import { useState } from 'react'
import { Card, Form, Input, Button, Upload, Avatar, message, Tabs, Descriptions, Tag } from 'antd'
import { UserOutlined, LockOutlined, CameraOutlined, SaveOutlined } from '@ant-design/icons'
import './index.scss'

const Profile = () => {
  const [loading, setLoading] = useState(false)
  const [activeTab, setActiveTab] = useState('info')
  const [isEditing, setIsEditing] = useState(false)
  const [form] = Form.useForm()
  const [passwordForm] = Form.useForm()

  // 模拟用户信息
  const [userInfo, setUserInfo] = useState({
    avatar: 'https://api.dicebear.com/7.x/lorelei/svg?seed=Admin',
    username: 'admin',
    realName: '管理员',
    email: 'admin@example.com',
    phone: '13800138000',
    role: '超级管理员',
    department: '技术部',
    createTime: '2023-01-15 10:30:00',
    lastLogin: '2024-01-20 14:25:30',
  })

  // 上传头像
  const handleAvatarChange = (info) => {
    if (info.file.status === 'done') {
      message.success('头像上传成功')
      // 这里应该更新头像URL
      setUserInfo({ ...userInfo, avatar: info.file.response.url })
    } else if (info.file.status === 'error') {
      message.error('头像上传失败')
    }
  }

  // 开始编辑
  const handleEdit = () => {
    setIsEditing(true)
  }

  // 取消编辑
  const handleCancel = () => {
    setIsEditing(false)
    form.setFieldsValue(userInfo)
  }

  // 保存基本信息
  const handleSaveInfo = async (values) => {
    setLoading(true)
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      setUserInfo({ ...userInfo, ...values })
      setIsEditing(false)
      message.success('保存成功')
    } catch (error) {
      message.error('保存失败')
    } finally {
      setLoading(false)
    }
  }

  // 修改密码
  const handleChangePassword = async (values) => {
    setLoading(true)
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      message.success('密码修改成功，请重新登录')
      passwordForm.resetFields()
    } catch (error) {
      message.error('密码修改失败')
    } finally {
      setLoading(false)
    }
  }

  // 基本信息Tab
  const InfoTab = () => (
    <div className="info-tab">
      <div className="info-content">
        <div className="avatar-section">
          <Avatar size={100} src={userInfo.avatar} icon={<UserOutlined />} />
          <Upload
            name="avatar"
            showUploadList={false}
            action="/api/upload/avatar"
            onChange={handleAvatarChange}
          >
            <Button icon={<CameraOutlined />} size="small" className="upload-btn">
              更换头像
            </Button>
          </Upload>
        </div>

        <div className="form-section">
          <div className="form-header">
            {!isEditing ? (
              <Button onClick={handleEdit}>
                编辑信息
              </Button>
            ) : (
              <div className="edit-actions">
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" loading={loading} onClick={() => form.submit()}>
                  保存
                </Button>
              </div>
            )}
          </div>
          
          <Form
            form={form}
            layout="vertical"
            initialValues={userInfo}
            onFinish={handleSaveInfo}
            className="info-form"
          >
            <Form.Item
              label="用户ID"
              name="username"
            >
              <Input disabled />
            </Form.Item>

            <Form.Item
              label="姓名"
              name="realName"
              rules={[{ required: true, message: '请输入真实姓名' }]}
            >
              <Input placeholder="请输入真实姓名" disabled={!isEditing} />
            </Form.Item>

            <Form.Item
              label="联系电话"
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
              ]}
            >
              <Input placeholder="13000000000" disabled={!isEditing} />
            </Form.Item>

            <Form.Item
              label="电子邮箱"
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="admin@test.com" disabled={!isEditing} />
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )

  // 账号信息Tab
  const AccountTab = () => (
    <div className="account-tab">
      <Descriptions bordered column={1} className="account-info">
        <Descriptions.Item label="用户名">{userInfo.username}</Descriptions.Item>
        <Descriptions.Item label="角色">
          <Tag color="blue">{userInfo.role}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="部门">{userInfo.department}</Descriptions.Item>
        <Descriptions.Item label="注册时间">{userInfo.createTime}</Descriptions.Item>
        <Descriptions.Item label="最后登录">{userInfo.lastLogin}</Descriptions.Item>
      </Descriptions>
    </div>
  )

  // 安全设置Tab
  const SecurityTab = () => (
    <div className="security-tab">
      <Form
        form={passwordForm}
        layout="vertical"
        onFinish={handleChangePassword}
        className="password-form"
      >
        <Form.Item
          label="旧密码"
          name="oldPassword"
          rules={[{ required: true, message: '请输入旧密码' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="请输入旧密码"
          />
        </Form.Item>

        <Form.Item
          label="新密码"
          name="newPassword"
          rules={[
            { required: true, message: '请输入新密码' },
            { min: 6, message: '密码至少6位' }
          ]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="请输入新密码"
          />
        </Form.Item>

        <Form.Item
          label="确认新密码"
          name="confirmPassword"
          dependencies={['newPassword']}
          rules={[
            { required: true, message: '请确认新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error('两次输入的密码不一致'))
              },
            }),
          ]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="请再次输入新密码"
          />
        </Form.Item>

        <Form.Item className="form-actions">
          <Button onClick={() => passwordForm.resetFields()}>
            取消
          </Button>
          <Button type="primary" htmlType="submit" loading={loading}>
            确认修改
          </Button>
        </Form.Item>
      </Form>
    </div>
  )

  return (
    <div className="profile-container">
      <Card className="profile-card">
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'info',
              label: '个人信息',
              children: <InfoTab />,
            },
            {
              key: 'security',
              label: '密码修改',
              children: <SecurityTab />,
            },
          ]}
        />
      </Card>
    </div>
  )
}

export default Profile
